package com.yicong.ants.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.utils.AppUtils;
import com.yicong.ants.utils.ConstantCodeUtils;
import com.yicong.ants.utils.IntentUtils;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.PermissionsChecker;
import com.yicong.ants.utils.QMUIStatusBarHelper;
import com.yicong.ants.utils.StringUtils;
import com.yicong.ants.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Activity基类
 */
public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = BaseActivity.class.getSimpleName();
    public Activity mContext;
    // 是否为深色模式
    public boolean isStatusBarLight = false;
    private PermissionsChecker.PermissionsCallBack callBack;
    // 尚未被允许的权限
    private List<String> needPermissions = null;

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void attachBaseContext(Context base) {
        Configuration config = base.getResources().getConfiguration();
        config.fontScale = 1F;
        Context context = createConfigurationContext(config);
        super.attachBaseContext(context);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setImmersion();
        if (!isStatusBarLight) {
            // L.e(TAG, "深色模式");
            // QMUIStatusBarHelper.setStatusBarLightMode(this);
            L.e(TAG, "浅色模式");
            QMUIStatusBarHelper.setStatusBarDarkMode(this);
        }
        // setTranslucentStatus();
        setContentView(getContentLayoutRes());
        // Eyes.setStatusBarColor(this, ContextCompat.getColor(this, R.color.gradual_bot));
        initDatas();
        initViews();
    }

    public void setImmersion() {

    }

    protected abstract int getContentLayoutRes();

    protected abstract void initDatas();

    protected abstract void initViews();

    public void showToast(String msg) {
        if (StringUtils.isNull(msg)) {
            L.e(Constants.DEBUG, "Toast msg 不能为空");
            return;
        }
        ToastUtils.showShort(this, msg);
    }

    public void requestPermission(String[] permissions, PermissionsChecker.PermissionsCallBack callBack) {
        needPermissions = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            callBack.PermissionsSuccess();
            return;
        }
        if (null == permissions || permissions.length <= 0) {
            return;
        }
        if (!PermissionsChecker.checkPermissions(mContext, permissions)) {
            this.callBack = callBack;
            request(permissions);
        } else {
            callBack.PermissionsSuccess();
        }
    }

    private void request(String[] permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, ConstantCodeUtils.PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean goSetting = false;
        for (int i = 0, y = permissions.length; i < y; i++) {
            // 判断该权限是否已经授权
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                // shouldShowRequestPermissionRationale合理的解释应该是：如果应用之前请求过此权限
                //但用户拒绝了请求且未勾选"Don’t ask again"，此方法将返回 true。
                //注：如果用户在过去拒绝了权限请求，并在权限请求系统对话框中勾选了 //"Don’t ask again" 选项，此方法将返回 false。如果设备规范禁止应用具有该权限，此方法会返回 false。
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!goSetting && !shouldShowRequestPermissionRationale(permissions[i])) {
                        goSetting = true;
                    }
                }
                if (null == needPermissions) {
                    needPermissions = new ArrayList<>();
                }
                needPermissions.add(permissions[i]);
            }
        }
        if (goSetting) {
            // 用户还是想用我的 APP 的 // 提示用户去应用设置界面手动开启权限
            AppUtils.goToAppSetting(this, null);
        }
        if (null == callBack) {
            return;
        }
        if (null == needPermissions) {
            callBack.PermissionsSuccess();
        } else {
            String[] values = new String[needPermissions.size()];
            request(needPermissions.toArray(values));
            callBack.PermissionsFailed(requestCode, needPermissions);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != ConstantCodeUtils.PERMISSION_REQUEST_CODE) {
            return;
        }
        String[] values = new String[needPermissions.size()];
        if (PermissionsChecker.checkPermissions(this, needPermissions.toArray(values))) {
            ToastUtils.showShort(this, "权限请求成功");
            needPermissions = null;
        }
    }

    /**
     * 数据异常
     */
    public void showDataException() {
        ToastUtils.showShort(this, getResources().getString(R.string.data_error));
    }

    /**
     * 网络异常
     */
    public void showNetWorkException() {
        ToastUtils.showShort(this, getResources().getString(R.string.net_error));
    }

    @Override
    public void finish() {
        super.finish();
        IntentUtils.exitAnim(this);
    }
}
